#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "error.h"








static int set(Error *err, const char *file, int line, int ecode, const char *string)
{
    if (err == NULL){
        return -1;
    }
    memset(err, 0, sizeof(*err));
    err->Line = line;
    err->Ecode = ecode;

    if (file != NULL){
        if (strlen(file) >= ERROR_PATH_MAX){
            strcpy(err->Path, "....");
            strcat(err->Path, &file[strlen(file) - ERROR_PATH_MAX + 4 + 1]);
        }else {
            strcpy(err->Path, file);
        }
    }
    if (string != NULL){
        if (strlen(string) >= ERROR_STRING_MAX){
            strcpy(err->String, "....");
            //"1234567890"
            strcat(err->String, &string[strlen(string) - ERROR_STRING_MAX + 4 + 1]);
        }else {
            strcpy(err->String, string);
        }
    }
    return 0;
}

static char *fullString(const Error *err)
{
    int 	byte_size = 0;
    char 	*fullString = NULL;

    if (!err){
        return NULL;
    }
    //fmt "%s#%5d#%d:%s"

    byte_size = strlen(err->Path) + 1 + 5 + 1 + 5 + 1 + strlen(err->String) + 1;
    fullString = calloc(1, byte_size);
    if (!fullString){
        return NULL;
    }
    sprintf(fullString, "%s#%5d#%5d:%s", err->Path, err->Line, err->Ecode, err->String);
    return fullString;
}

static char *string(const Error *err)
{
    char 	*string = NULL;

    if (!err){
        return NULL;
    }

    string = calloc(1, strlen(err->String) + 1);
    if (!string){
        return NULL;
    }
    strcpy(string, err->String);
    return string;
}
static void freeString(char *string)
{
    if (string){
        free(string);
    }
}

const struct error_interface moduleError = {
    set,
    fullString,
    string,
    freeString
};

















